package com.stylefeng.guns.modular.train.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.guns.common.constant.MvcResult;
import com.stylefeng.guns.common.persistence.model.Employee;
import com.stylefeng.guns.common.persistence.model.ProjectAuthenPoints;
import com.stylefeng.guns.common.persistence.model.QualityGradeRule;
import com.stylefeng.guns.config.excel.ExcelExportStylerImpl;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.ErrorTip;
import com.stylefeng.guns.core.base.tips.SuccessTip;
import com.stylefeng.guns.core.util.BeanUtils;
import com.stylefeng.guns.modular.system.service.IDictService;
import com.stylefeng.guns.modular.system.service.IQualityGradeRuleService;
import com.stylefeng.guns.modular.train.service.IEmployeeService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.common.persistence.model.TrainerAuthenPoints;
import com.stylefeng.guns.modular.train.service.ITrainerAuthenPointsService;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.stylefeng.guns.common.constant.Const;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * trainerAuthenPoints控制器
 *
 * @author fengshuonan
 * @Date 2018-01-24 21:30:31
 */
@Controller
@RequestMapping("/trainerAuthenPoints")
public class TrainerAuthenPointsController extends BaseController {

    private String PREFIX = "/train/trainerAuthenPoints/";

    @Autowired
    private ITrainerAuthenPointsService trainerAuthenPointsService;

    @Autowired
    private IDictService dictService;

    @Autowired
    private IQualityGradeRuleService qualityGradeRuleService;

    @Autowired
    private IEmployeeService employeeService;

    private static List<TrainerAuthenPoints> REPEAT = new ArrayList<>();

    /**
     * 跳转到trainerAuthenPoints首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "trainerAuthenPoints.html";
    }

    /**
     * 跳转到添加trainerAuthenPoints
     */
    @RequestMapping("/trainerAuthenPoints_add")
    public String trainerAuthenPointsAdd(Model model) {

        model.addAttribute("au_majors", dictService.getByPCode("au_major"));
        model.addAttribute("authens", qualityGradeRuleService.getByGradeType(Const.TRAINER_LEVEL_AUTHENTICATION));
        return PREFIX + "trainerAuthenPoints_add.html";
    }

    /**
     * 跳转到修改trainerAuthenPoints
     */
    @RequestMapping("/trainerAuthenPoints_update/{trainerAuthenPointsId}")
    public String trainerAuthenPointsUpdate(@PathVariable String trainerAuthenPointsId, Model model) {
        TrainerAuthenPoints trainerAuthenPoints = trainerAuthenPointsService.selectById(trainerAuthenPointsId);
        model.addAttribute("au_majors", dictService.getByPCode("au_major"));
        model.addAttribute("authens", qualityGradeRuleService.getByGradeType(Const.TRAINER_LEVEL_AUTHENTICATION));
        model.addAttribute("item",trainerAuthenPoints);
        LogObjectHolder.me().set(trainerAuthenPoints);
        return PREFIX + "trainerAuthenPoints_edit.html";
    }

    /**
     * 获取trainerAuthenPoints列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(Employee employee, Double min, Double max) {
        if(BeanUtils.checkFieldValueNull(employee) && min == null && max == null){
            List<TrainerAuthenPoints> trainerAuthenPointss = trainerAuthenPointsService.selectList(null);
            trainerAuthenPointss.forEach(t->{
                if(t.getIssuingDate() != null){
                    t.setStrIssuingDate(Const.df.format(t.getIssuingDate()));
                }
            });
            return trainerAuthenPointss;
        }

        EntityWrapper<Employee> wrapper = new EntityWrapper<>();
        wrapper.setEntity(employee);
        List<Employee> employees = employeeService.selectList(wrapper);
        Set<String> empCodes = new HashSet<>();
        employees.forEach(e -> empCodes.add(e.getEmpCode()));

        List<TrainerAuthenPoints> list = new ArrayList<>();
        if(!empCodes.isEmpty()){
            EntityWrapper<TrainerAuthenPoints> nwWrapper = new EntityWrapper<>();
            nwWrapper.in("emp_code",empCodes);

            if(min != null || max != null){
                min = min == null ? 0.0 : min;
                max = max == null ? 9999.0 : max;

                nwWrapper.between("integral",min,max);
            }

            list= trainerAuthenPointsService.selectList(nwWrapper);
        }
        list.forEach(t->{
            if(t.getIssuingDate() != null){
                t.setStrIssuingDate(Const.df.format(t.getIssuingDate()));
            }
        });
        return list;
    }
    /**
     * 新增trainerAuthenPoints
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(TrainerAuthenPoints trainerAuthenPoints) {
        trainerAuthenPoints.setCreateDate(new Date());
        trainerAuthenPoints.setDataOrigin(Const.IMPORT_TYPE_SYS);
        trainerAuthenPointsService.insert(trainerAuthenPoints);
        return super.SUCCESS_TIP;
    }

    @RequestMapping(value = "/adds")
    @ResponseBody
    public Object adds(@RequestBody TrainerAuthenPoints[] repeatData) {

        List<TrainerAuthenPoints> trainerAuthenPointss = Arrays.asList(repeatData);

        Date now = new Date();
        List<QualityGradeRule> qualityGradeRules=qualityGradeRuleService.getByGradeType(Const.TRAINER_LEVEL_AUTHENTICATION);
        trainerAuthenPointss.forEach(trainerAuthenPoints -> {
            trainerAuthenPoints.setDataOrigin(Const.IMPORT_TYPE_XML);
            trainerAuthenPoints.setCreateDate(now);
            qualityGradeRules.forEach(item->{
                if(item.getGrade().equals(trainerAuthenPoints.getAuthen())){
                    trainerAuthenPoints.setAuthenCode(item.getGradeCode());
                    trainerAuthenPoints.setIntegral(item.getIntegral());
                }
            });
        });

        trainerAuthenPointsService.insertBatch(trainerAuthenPointss);
        return super.SUCCESS_TIP;
    }

    /**
     * 删除trainerAuthenPoints
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam String trainerAuthenPointsId) {
        if(trainerAuthenPointsId.contains(",")){
            List<String> ids = Arrays.asList(trainerAuthenPointsId.split(","));
            trainerAuthenPointsService.deleteBatchIds(ids);
        }else{
            trainerAuthenPointsService.deleteById(trainerAuthenPointsId);
        }
        return SUCCESS_TIP;
    }

    /**
     * 修改trainerAuthenPoints
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(TrainerAuthenPoints trainerAuthenPoints) {
        trainerAuthenPointsService.updateById(trainerAuthenPoints);
        return super.SUCCESS_TIP;
    }

    /**
     * trainerAuthenPoints详情
     */
    @RequestMapping(value = "/detail/{trainerAuthenPointsId}")
    @ResponseBody
    public Object detail(@PathVariable("trainerAuthenPointsId") String trainerAuthenPointsId) {
        return trainerAuthenPointsService.selectById(trainerAuthenPointsId);
    }

    /**
     * 跳转到导入ContestPoints
     */
    @RequestMapping("/trainerAuthenPoints_import")
    public String contestPointsImport() {
        return PREFIX + "trainerAuthenPoints_import.html";
    }

    /**
     * 导入trainerAuthenPoints
     */
    @RequestMapping(value = "/import")
    @ResponseBody
    public Object imports(MultipartHttpServletRequest mutReq) {

        ImportParams params = new ImportParams();
        params.setStartRows(0);
        params.setTitleRows(1);

        int count = 2;

        try {
            List<TrainerAuthenPoints> trainerAuthenPointss = ExcelImportUtil.importExcel(mutReq.getFile("file").getInputStream(), TrainerAuthenPoints.class, params);
            Date now = new Date();

            Map<String, String> nameAndCode = employeeService.getNameAndCode();
            List<TrainerAuthenPoints> noRepeat = new ArrayList<>();
            List<TrainerAuthenPoints> hasNameList = new ArrayList<>();

            List<QualityGradeRule> qualityGradeRules=qualityGradeRuleService.getByGradeType(Const.TRAINER_LEVEL_AUTHENTICATION);

            for (TrainerAuthenPoints trainerAuthenPoints : trainerAuthenPointss) {
                trainerAuthenPoints.setDataOrigin(Const.IMPORT_TYPE_XML);
                trainerAuthenPoints.setCreateDate(now);

                if(StringUtils.isEmpty(trainerAuthenPoints.getEmpCode())) {
                    //姓名检测
                    if (nameAndCode.containsKey(trainerAuthenPoints.getEmpName())) {
                        //有该姓名，检测是否重名
                        if (nameAndCode.get(trainerAuthenPoints.getEmpName()).contains(",")) {
                            //有重名情况
                            trainerAuthenPoints.setEmpCode(Const.DEFAULT_CODE);
                            REPEAT.add(trainerAuthenPoints);
                        } else {
                            //无重名、正常插入
                            trainerAuthenPoints.setEmpCode(nameAndCode.get(trainerAuthenPoints.getEmpName()));

                            qualityGradeRules.forEach(item->{
                                if(item.getGrade().equals(trainerAuthenPoints.getAuthen())){
                                    trainerAuthenPoints.setAuthenCode(item.getGradeCode());
                                    trainerAuthenPoints.setIntegral(item.getIntegral());
                                }
                            });

                            noRepeat.add(trainerAuthenPoints);
                        }
                    } else {
                        throw new Exception("姓名为 " + trainerAuthenPoints.getEmpName() + " 在员工管理中不存在!");
                    }
                }else{
                    qualityGradeRules.forEach(item->{
                        if(item.getGrade().equals(trainerAuthenPoints.getAuthen())){
                            trainerAuthenPoints.setAuthenCode(item.getGradeCode());
                            trainerAuthenPoints.setIntegral(item.getIntegral());
                        }
                    });

                    hasNameList.add(trainerAuthenPoints);
                }

                count++;
            }
            //不重复，先插入
            if(noRepeat.size() > 0){
                trainerAuthenPointsService.insertBatch(noRepeat);
            }
            if(hasNameList.size() > 0){
                trainerAuthenPointsService.insertBatch(hasNameList);
            }
            //处理重复数据
            if(!REPEAT.isEmpty()){
                MvcResult mvcResult = new MvcResult();
                mvcResult.setData(REPEAT);

                return mvcResult;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ErrorTip(400,"第"+ count+"条 " +e.getMessage());
        }

        SuccessTip successTip = super.SUCCESS_TIP;
        successTip.setMessage(String.format("成功插入%d", count-2)  + "条数据");
        return successTip;
    }

    @RequestMapping("/repeat")
    public String repeat(Model model){
        model.addAttribute("repeat", JSON.toJSONString(REPEAT));

        //消费后清空
        REPEAT = new ArrayList<>();
        return PREFIX + "repeat.html";
    }

    /**
     * 导出
     */
    @RequestMapping(value = "/export")
    @ResponseBody
    public void export(HttpServletRequest request, HttpServletResponse response) {
        try {
            List<TrainerAuthenPoints> trainerAuthenPoints= trainerAuthenPointsService.selectList(null);
            ExportParams exportParams=new ExportParams("认证兼职培训师积分统计表", "认证兼职培训师积分统计表");
            exportParams.setStyle(ExcelExportStylerImpl.class);
            exportParams.setTitleHeight((short)14);
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, TrainerAuthenPoints.class, trainerAuthenPoints);
            OutputStream outputStream=response.getOutputStream();
            String fileName="认证兼职培训师积分统计表.xls";
            response.addHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(),"ISO-8859-1"));
            workbook.write(outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
